package com.nuc.iblog.service.imp;

import com.nuc.iblog.entity.UserLove;
import com.nuc.iblog.jpa.ArticleJpa;
import com.nuc.iblog.jpa.UserJpa;
import com.nuc.iblog.jpa.UserLoveJpa;
import com.nuc.iblog.service.ClUserLoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

@Service
public class ClUserLoveServiceimp implements ClUserLoveService {
    @Autowired
    private UserLoveJpa userLoveJpa;
    @Autowired
    private UserJpa userJpa;
    @Autowired
    private ArticleJpa articleJpa;
    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);

        this.redisTemplate = redisTemplate;
    }

    @Override
    public int love(int uid, int aid) {
        UserLove userLove=userLoveJpa.findByUserAndArticle(userJpa.getOne(uid),articleJpa.getOne(aid));
        int alove=Integer.parseInt((String) redisTemplate.opsForValue().get(String.valueOf(aid)));
        if (userLove!=null){
            redisTemplate.opsForValue().set(String.valueOf(aid),String.valueOf(alove-1));
            userLoveJpa.delete(userLove);
            return -1;
        }
        else{
            userLove=new UserLove();
            redisTemplate.opsForValue().set(String.valueOf(aid),String.valueOf(alove+1));
        }
        userLove.setUser(userJpa.getOne(uid));
        userLove.setArticle(articleJpa.getOne(aid));
        userLoveJpa.save(userLove);
        return 1;
    }

    @Override
    public int lovestatus(int uid, int aid) {
        UserLove userLove=userLoveJpa.findByUserAndArticle(userJpa.getOne(uid),articleJpa.getOne(aid));
        if(userLove==null)
            return -1;
        else
            return 1;
    }
}
